package com.neuedu.his5.exception;

import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


// @RestControllerAdvice 会自动将返回值转为 JSON，无需额外加 @ResponseBody
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    // 捕获所有未处理的异常（可根据需要细化，如指定特定异常类型）
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleAllExceptions(Exception e, HttpServletRequest request) {
        logger.error("请求 {} 发生异常: {}", request.getRequestURL(), e.getMessage(), e);

        ErrorResponse errorResponse = new ErrorResponse(
                HttpStatus.INTERNAL_SERVER_ERROR.value(),
                "服务器内部错误，请稍后重试",
                e.getMessage() // 生产环境建议隐藏具体异常信息，避免暴露敏感内容
        );
        return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    // 示例：处理特定异常（如空指针），可针对性返回更友好信息
    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity<ErrorResponse> handleNullPointerException(NullPointerException e, HttpServletRequest request) {
        logger.error("请求 {} 发生空指针异常: {}", request.getRequestURL(), e.getMessage(), e);

        ErrorResponse errorResponse = new ErrorResponse(
                HttpStatus.BAD_REQUEST.value(),
                "参数错误或数据未正确初始化",
                e.getMessage()
        );
        return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
    }

    // 自定义错误响应体（根据需求设计结构）
    static class ErrorResponse {
        private int code;
        private String message;
        private String detail;

        public ErrorResponse(int code, String message, String detail) {
            this.code = code;
            this.message = message;
            this.detail = detail;
        }

        // Getter、Setter 略
    }
}